package com.example.sakurasay.passwordbook.data.daos

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.example.sakurasay.passwordbook.data.entities.SharedAccount
import com.example.sakurasay.passwordbook.data.entities.SharedPassword
import com.example.sakurasay.passwordbook.data.relations.SharedPasswordWithAccounts
import kotlinx.coroutines.flow.Flow

@Dao
interface SharedPasswordDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertSharedPassword(password: SharedPassword): Long

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertSharedAccount(account: SharedAccount)

    @Update
    suspend fun updateSharedPassword(password: SharedPassword)

    @Update
    suspend fun updateSharedAccount(account: SharedAccount)

    @Delete
    suspend fun deleteSharedPassword(password: SharedPassword)

    @Delete
    suspend fun deleteSharedAccount(account: SharedAccount)

    @Query("SELECT * FROM shared_passwords ORDER BY password_name ASC")
    fun getAllSharedPasswords(): Flow<List<SharedPassword>>

    @Query("SELECT * FROM shared_accounts WHERE password_id = :passwordId")
    fun getAccountsForPassword(passwordId: Int): Flow<List<SharedAccount>>

    @Transaction
    @Query("SELECT * FROM shared_passwords WHERE password_name LIKE :searchQuery")
    fun searchSharedPasswords(searchQuery: String): Flow<List<SharedPassword>>

    @Transaction
    @Query("SELECT * FROM shared_passwords")
    fun getSharedPasswordsWithAccounts(): Flow<List<SharedPasswordWithAccounts>>
}